const router = require('express').Router()
const pool = require('../db/pool.js')

router.get('/goods/all/:pageIndex/:pageSize', async (req, res) => {
  let { pageIndex, pageSize } = req.params
  let sql = `select * from goods limit ${ pageSize * (pageIndex - 1) }, ${ pageSize }`
  const result = await pool.query(sql)
  res.status(200).json(result[0])
})

router.get('/goods/search/:name', async (req, res) => {
  let { name } = req.params
  let { order, orderName } = req.query
  let sql = `select * from goods where name like '%${ name }%'`
  
  if (orderName && orderName !== 'none') {
    sql += ` order by ${ orderName }`
    if (order) sql += ` ${ order }`
  }

  console.log(sql)

  const result = await pool.query(sql)
  res.status(200).json(result[0])
})

router.get('/goods/:id', async (req, res) => {
  let { id } = req.params
  let sql = `select * from goods where id = ${ id }`
  const result = await pool.query(sql)
  res.status(200).json(result[0][0])
})


module.exports = router